/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frames;

import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * The <code>CreateTableFrame<code> is used to create a table in the connected database. A connection is
 * established with the database name, user name and password given by the user. 
 *<p>
 * For creating a table there should be at least one row with accurate data in the new table. Otherwise, a
 * <code>RuntimeException<code> is thrown and the user gets an appropriate message.
 * 
 * @author Mariya Valcheva
 *@version 1.0
 */
public class CreateTableFrame extends javax.swing.JFrame {

    /* Parameters from constructor */
    private Connection connection;
    private String databaseName; 
    
    /**
     * Creates new table frame. The constructor gets the connection and database parameters.
     * @param conn the connection with a specific database.
     * @param dbName the database's name.
     */
    public CreateTableFrame(final Connection conn,
                            final String dbName) {
        
        connection = conn;
        databaseName = dbName;
        
        initComponents();
        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     * <p>
     * Initializes the frame's components.
     * Constructs the whole panel.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpfPanelFrame = new javax.swing.JPanel();
        jptpPanelTabbedPane = new javax.swing.JPanel();
        jTabbedPane = new javax.swing.JTabbedPane();
        jpcPanelColumn = new javax.swing.JPanel();
        jpcLabelTableName = new javax.swing.JLabel();
        jpcTextFieldTableName = new javax.swing.JTextField();
        jpcLabelSchema = new javax.swing.JLabel();
        jpcTextFieldSchema = new javax.swing.JTextField();
        jpcScrollPane = new javax.swing.JScrollPane();
        jpcTable = new javax.swing.JTable();
        jpcButtonAddColumn = new javax.swing.JButton();
        jpcButtonDeleteColumn = new javax.swing.JButton();
        jpcLabelColumnName = new javax.swing.JLabel();
        jpcLabelDataType = new javax.swing.JLabel();
        jpcCheckBoxPK = new javax.swing.JCheckBox();
        jpcCheckBoxNN = new javax.swing.JCheckBox();
        jpcTextColumnName = new javax.swing.JTextField();
        jpcTextDataType = new javax.swing.JTextField();
        jpfkPanelFK = new javax.swing.JPanel();
        jpfkPanelFKI = new javax.swing.JPanel();
        jpfkScrollPane = new javax.swing.JScrollPane();
        jpfkTable = new javax.swing.JTable();
        jpfkButtonAddFK = new javax.swing.JButton();
        jpfkButtonDeleteFK = new javax.swing.JButton();
        jpfkLabelFKN = new javax.swing.JLabel();
        jpfkTextFKN = new javax.swing.JTextField();
        jpfkLabelColumn = new javax.swing.JLabel();
        jpfkTextColumn = new javax.swing.JTextField();
        jpfkLabelRefTable = new javax.swing.JLabel();
        jpfkTextRefTable = new javax.swing.JTextField();
        jpfkLabelRefColumn = new javax.swing.JLabel();
        jpfkTextRefColumn = new javax.swing.JTextField();
        jButtonSave = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);

        jTabbedPane.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jpcLabelTableName.setText("Table Name:");

        jpcLabelSchema.setText("Schema:");

        jpcTextFieldSchema.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpcTextFieldSchemaActionPerformed(evt);
            }
        });

        /**
         * Constructs the new table to be populated with the new user's data. 
         */
        jpcTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Column Name", "Datatype", "Primary Key", "Not Null"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jpcScrollPane.setViewportView(jpcTable);

        jpcButtonAddColumn.setText("Add Column");
        jpcButtonAddColumn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpcButtonAddColumnActionPerformed(evt);
            }
        });

        jpcButtonDeleteColumn.setText("Delete Column");
        jpcButtonDeleteColumn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpcButtonDeleteColumnActionPerformed(evt);
            }
        });

        jpcLabelColumnName.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jpcLabelColumnName.setText("Column Name:");

        jpcLabelDataType.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jpcLabelDataType.setText("Data Type:");

        jpcCheckBoxPK.setText("Primary Key:");
        jpcCheckBoxPK.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);

        jpcCheckBoxNN.setText("Not Null:");
        jpcCheckBoxNN.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);

        /**
         * Constructs the first panel consisting the columns of the new table.
         */
        javax.swing.GroupLayout jpcPanelColumnLayout = new javax.swing.GroupLayout(jpcPanelColumn);
        jpcPanelColumn.setLayout(jpcPanelColumnLayout);
        jpcPanelColumnLayout.setHorizontalGroup(
            jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpcScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                    .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                        .addComponent(jpcLabelTableName)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpcTextFieldTableName, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jpcLabelSchema)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpcTextFieldSchema))
                    .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                        .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jpcButtonAddColumn)
                                .addComponent(jpcLabelColumnName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jpcLabelDataType, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jpcButtonDeleteColumn))
                            .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                                .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jpcTextDataType, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jpcTextColumnName, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jpcCheckBoxNN)
                            .addComponent(jpcCheckBoxPK))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jpcPanelColumnLayout.setVerticalGroup(
            jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpcPanelColumnLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpcLabelTableName)
                    .addComponent(jpcTextFieldTableName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpcLabelSchema)
                    .addComponent(jpcTextFieldSchema, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jpcScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpcButtonAddColumn)
                    .addComponent(jpcButtonDeleteColumn))
                .addGap(18, 18, 18)
                .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpcLabelColumnName)
                    .addComponent(jpcTextColumnName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpcPanelColumnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpcLabelDataType)
                    .addComponent(jpcTextDataType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jpcCheckBoxPK)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpcCheckBoxNN)
                .addGap(82, 82, 82))
        );

        jTabbedPane.addTab("Columns", jpcPanelColumn);

        /**
         * Constructs the second tabbedpanel - foreign keys.
         */
        jpfkPanelFKI.setBorder(javax.swing.BorderFactory.createTitledBorder("Foreign Keys"));

        jpfkTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Foreign Key Name", "Column", "Referenced Table", "Referenced Column"
            }
        ));
        jpfkScrollPane.setViewportView(jpfkTable);

        jpfkButtonAddFK.setText("Add Foreign Key");
        jpfkButtonAddFK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpfkButtonAddFKActionPerformed(evt);
            }
        });

        jpfkButtonDeleteFK.setText("Delete Foreign Key");
        jpfkButtonDeleteFK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpfkButtonDeleteFKActionPerformed(evt);
            }
        });

        jpfkLabelFKN.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jpfkLabelFKN.setText("Foreign Key Name:");

        jpfkLabelColumn.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jpfkLabelColumn.setText("Column:");

        jpfkLabelRefTable.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jpfkLabelRefTable.setText("Referenced Table:");

        jpfkLabelRefColumn.setText("Referenced Column:");

        javax.swing.GroupLayout jpfkPanelFKILayout = new javax.swing.GroupLayout(jpfkPanelFKI);
        jpfkPanelFKI.setLayout(jpfkPanelFKILayout);
        jpfkPanelFKILayout.setHorizontalGroup(
            jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpfkPanelFKILayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpfkLabelFKN, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpfkLabelColumn, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpfkLabelRefTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpfkLabelRefColumn, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jpfkTextFKN, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                    .addComponent(jpfkTextColumn, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                    .addComponent(jpfkTextRefTable)
                    .addComponent(jpfkTextRefColumn))
                .addContainerGap())
            .addGroup(jpfkPanelFKILayout.createSequentialGroup()
                .addComponent(jpfkButtonAddFK)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jpfkButtonDeleteFK))
            .addComponent(jpfkScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
        );
        jpfkPanelFKILayout.setVerticalGroup(
            jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpfkPanelFKILayout.createSequentialGroup()
                .addComponent(jpfkScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpfkButtonAddFK)
                    .addComponent(jpfkButtonDeleteFK))
                .addGap(18, 18, 18)
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpfkLabelFKN)
                    .addComponent(jpfkTextFKN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jpfkLabelColumn)
                    .addComponent(jpfkTextColumn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpfkLabelRefTable)
                    .addComponent(jpfkTextRefTable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpfkPanelFKILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpfkLabelRefColumn)
                    .addComponent(jpfkTextRefColumn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 78, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jpfkPanelFKLayout = new javax.swing.GroupLayout(jpfkPanelFK);
        jpfkPanelFK.setLayout(jpfkPanelFKLayout);
        jpfkPanelFKLayout.setHorizontalGroup(
            jpfkPanelFKLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpfkPanelFKLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpfkPanelFKI, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jpfkPanelFKLayout.setVerticalGroup(
            jpfkPanelFKLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpfkPanelFKLayout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jpfkPanelFKI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(60, Short.MAX_VALUE))
        );

        jTabbedPane.addTab("Foreign Keys", jpfkPanelFK);

        javax.swing.GroupLayout jptpPanelTabbedPaneLayout = new javax.swing.GroupLayout(jptpPanelTabbedPane);
        jptpPanelTabbedPane.setLayout(jptpPanelTabbedPaneLayout);
        jptpPanelTabbedPaneLayout.setHorizontalGroup(
            jptpPanelTabbedPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptpPanelTabbedPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane)
                .addContainerGap())
        );
        jptpPanelTabbedPaneLayout.setVerticalGroup(
            jptpPanelTabbedPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jptpPanelTabbedPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane)
                .addContainerGap())
        );

        javax.swing.GroupLayout jpfPanelFrameLayout = new javax.swing.GroupLayout(jpfPanelFrame);
        jpfPanelFrame.setLayout(jpfPanelFrameLayout);
        jpfPanelFrameLayout.setHorizontalGroup(
            jpfPanelFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpfPanelFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jptpPanelTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jpfPanelFrameLayout.setVerticalGroup(
            jpfPanelFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpfPanelFrameLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jptpPanelTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButtonSave.setText("Save");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpfPanelFrame, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jButtonSave)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpfPanelFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonSave)
                .addGap(0, 3, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jpcTextFieldSchemaActionPerformed(java.awt.event.ActionEvent evt) {
        
    }

    /**
     * Handles the actions performed after the DeleteColumn button is pushed. The selected rows are firstly
     * sorted and then removed from the table in order to be preserved right indexing of the remained rows.
     * @param evt the invoked action event.
     */
    private void jpcButtonDeleteColumnActionPerformed(java.awt.event.ActionEvent evt) {
        int[] selectedRows = jpcTable.getSelectedRows(); 
        if (selectedRows.length > 0) {
            DefaultTableModel tableModel = (DefaultTableModel) jpcTable.getModel();            
            Arrays.sort(selectedRows);
            
            for (int r = selectedRows.length - 1; r > -1; r --) {
                int row = selectedRows[r]; 
                tableModel.removeRow(row);
            }            
        }
    }
/**
 * Firstly executes a drop table statement for the table with the given name. If the last doesn't exist 
 * throws a <code>SQLException<code>. At both cases executes the create statement.
 * @param evt
 */
    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {
        dropTable();
        executeCreateTableStatement();
    }
    
/**
 * Drops the table if the last exists. Otherwise, throws a <code>SQLException<code>.
 * @throws HeadlessException
 */
   private void dropTable() throws HeadlessException {
        String dropTableQry = "drop table " + databaseName + "." + jpcTextFieldTableName.getText();
        Statement dropTableStmt = null; 
         
        try {
            dropTableStmt = connection.createStatement();
            dropTableStmt.execute(dropTableQry);            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } finally {
            if (dropTableStmt != null) {
                try {
                    dropTableStmt.close();
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                }
            }
        }
    }

   /**
    * Firstly prepares the create statement invoking prepareCreateTableQry() and if the operation is successful
    *  executes it.
    */
    private void executeCreateTableStatement() {               
        String createTableQry =  null;
        try {
            createTableQry = prepareCreateTableQry();
        } catch (RuntimeException rex) {
            JOptionPane.showMessageDialog(null, rex.getMessage());            
        }
            
        if (createTableQry != null) {
            Statement createTableStmt = null;          
            try {
                createTableStmt = connection.createStatement();
                createTableStmt.execute(createTableQry);            
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } finally {
                if (createTableStmt != null) {
                    try {
                        createTableStmt.close();
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            }      
        }  
    }
        
/**
 * Prepares the create statement. Checks if the table is empty, throws a <code>RuntimeException<code> and 
 * informs the user about the problem. Otherwise, constructs the statement with the table data.
 *     
 * @return the constructed create statement.
 */
    private String prepareCreateTableQry() {                
        DefaultTableModel columnsModel = (DefaultTableModel) jpcTable.getModel();
        int columnsCount = columnsModel.getRowCount();
        
        if (columnsCount == 0) {
            throw new RuntimeException("Insert at least one column !!!");
        }
                
        StringBuilder createStmtQryBuilder = new StringBuilder(); 
        createStmtQryBuilder.append("create table " + jpcTextFieldTableName.getText() + " (\n");
        
        // add columns 
        for (int r = 0; r < columnsCount; r ++) {
            if (r > 0) {
                createStmtQryBuilder.append(",\n");
            }
            
            // add column name 
            createStmtQryBuilder.append(columnsModel.getValueAt(r, 0) + " ");
            // add column type
            createStmtQryBuilder.append(columnsModel.getValueAt(r, 1) + " ");
            
            // add not null  
            boolean isNN = (Boolean) columnsModel.getValueAt(r, 3);
            if (isNN) {
                createStmtQryBuilder.append("NOT NULL" + " ");
            }
            
            // add primary key   
            boolean isPK = (Boolean) columnsModel.getValueAt(r, 2);
            if (isPK) {
                createStmtQryBuilder.append("PRIMARY KEY" + " ");
            }
        }
        
        DefaultTableModel fkModel = (DefaultTableModel) jpfkTable.getModel();
        int fkCount = fkModel.getRowCount();
        
        // add foreign key 
        for (int r = 0; r < fkCount; r ++) {
            createStmtQryBuilder.append(",\n");
               
            // add foreign key name  
            createStmtQryBuilder.append(" CONSTRAINT " + fkModel.getValueAt(r, 0) + " ");
            
            // add foreign key column  
            createStmtQryBuilder.append("FOREIGN KEY (" + fkModel.getValueAt(r, 1) + ") ");
            // add foreign table and foreign column 
            createStmtQryBuilder.append("REFERENCES " + fkModel.getValueAt(r, 2) + "(" + fkModel.getValueAt(r, 3) + ") ");
        }
        
        createStmtQryBuilder.append("\n)");
                    
        return createStmtQryBuilder.toString();
    }
 /**
  * Adds a new row at the end of the <code>JTable<code> holding the column's data.
  * @param evt the <code>ActionEvent<code>.
  */
    private void jpcButtonAddColumnActionPerformed(java.awt.event.ActionEvent evt) {
        DefaultTableModel tableModel = (DefaultTableModel) jpcTable.getModel();
        tableModel.addRow(new Object[] {
            jpcTextColumnName.getText(), 
            jpcTextDataType.getText(), 
            jpcCheckBoxPK.isSelected(), 
            jpcCheckBoxNN.isSelected()            
        });  
    }

/**
 * Adds a new row at the end of the <code>JTable<code> holding the foreign key information.
 * @param evt the <code>ActionEvent<code>.
 */
    private void jpfkButtonAddFKActionPerformed(java.awt.event.ActionEvent evt) {
        DefaultTableModel tableModel = (DefaultTableModel) jpfkTable.getModel();
        tableModel.addRow(new Object[] {
            jpfkTextFKN.getText(), 
            jpfkTextColumn.getText(), 
            jpfkTextRefTable.getText(), 
            jpfkTextRefColumn.getText()            
        });  
    }

/**
 *Deletes the last row from the <code>JTable<code> holding the foreign key information.     
 * @param evt the <code>ActionEvent<code>.
 */
    private void jpfkButtonDeleteFKActionPerformed(java.awt.event.ActionEvent evt) {
        int[] selectedRows = jpfkTable.getSelectedRows(); 
        if (selectedRows.length > 0) {
            DefaultTableModel tableModel = (DefaultTableModel) jpfkTable.getModel();            
            Arrays.sort(selectedRows);
            
            for (int r = selectedRows.length - 1; r > -1; r --) {
                int row = selectedRows[r]; 
                tableModel.removeRow(row);
            }            
        }
    }

    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonSave;
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JButton jpcButtonAddColumn;
    private javax.swing.JButton jpcButtonDeleteColumn;
    private javax.swing.JCheckBox jpcCheckBoxNN;
    private javax.swing.JCheckBox jpcCheckBoxPK;
    private javax.swing.JLabel jpcLabelColumnName;
    private javax.swing.JLabel jpcLabelDataType;
    private javax.swing.JLabel jpcLabelSchema;
    private javax.swing.JLabel jpcLabelTableName;
    private javax.swing.JPanel jpcPanelColumn;
    private javax.swing.JScrollPane jpcScrollPane;
    private javax.swing.JTable jpcTable;
    private javax.swing.JTextField jpcTextColumnName;
    private javax.swing.JTextField jpcTextDataType;
    private javax.swing.JTextField jpcTextFieldSchema;
    private javax.swing.JTextField jpcTextFieldTableName;
    private javax.swing.JPanel jpfPanelFrame;
    private javax.swing.JButton jpfkButtonAddFK;
    private javax.swing.JButton jpfkButtonDeleteFK;
    private javax.swing.JLabel jpfkLabelColumn;
    private javax.swing.JLabel jpfkLabelFKN;
    private javax.swing.JLabel jpfkLabelRefColumn;
    private javax.swing.JLabel jpfkLabelRefTable;
    private javax.swing.JPanel jpfkPanelFK;
    private javax.swing.JPanel jpfkPanelFKI;
    private javax.swing.JScrollPane jpfkScrollPane;
    private javax.swing.JTable jpfkTable;
    private javax.swing.JTextField jpfkTextColumn;
    private javax.swing.JTextField jpfkTextFKN;
    private javax.swing.JTextField jpfkTextRefColumn;
    private javax.swing.JTextField jpfkTextRefTable;
    private javax.swing.JPanel jptpPanelTabbedPane;
    // End of variables declaration//GEN-END:variables
}
